package com.ldy.db;

import com.ldy.util.AnnotationUtil;

public class QueryBuilder<T> {

	private StringBuilder mQueryBuilder = new StringBuilder();

	private Where<T> mWhere;

	private boolean distinct;
	
	private String mColumns;
	
	private Class mClz;
	
	public QueryBuilder(Class cla) { 
		mClz = cla;
	}
	
	public QueryBuilder<T> clear() {
		mQueryBuilder = new StringBuilder();
		return this;
	}

	/**
	 * 是否去除重复行
	 * 
	 * @return
	 */
	public QueryBuilder<T> distinct() {
		distinct = true;
		return this;
	}

	public QueryBuilder<T> groupBy(String obj) {
		return this;
	}

	public QueryBuilder<T> groupByRaw(String obj) {
		return this;
	}

	public QueryBuilder<T> having(String obj) {
		return this;
	}

	public QueryBuilder<T> join(QueryBuilder<?> query) {
		return this;
	}

	public QueryBuilder<T> leftJoin(QueryBuilder<?> query) {
		return this;
	}

	public QueryBuilder<T> limit(int limit) {
		return this;
	}

	public QueryBuilder<T> offset(int start) {
		return this;
	}

	public QueryBuilder<T> orderBy(String str) {
		return this;
	}

	public QueryBuilder<T> queryForFirst() {
		return this;
	}

	public QueryBuilder<T> selectColumns(String... columns) {

		if (distinct) {
			mQueryBuilder.append(" select distinct ");
		} else {
			mQueryBuilder.append(" select ");
		}
		for (String string : columns) {
			mQueryBuilder.append(string + " ,");
		}

		mQueryBuilder.delete(mQueryBuilder.length() - 1, mQueryBuilder.length());

		return this;
	}

	public void setWhere(Where<T> where) {
		mWhere = where;
	}

	public String createSQL() {
		
		if(mColumns == null) {
			mQueryBuilder.append(" select * from " + AnnotationUtil.getTableName(mClz));
		}
		
		if (mWhere != null) {
			mQueryBuilder.append(" where " + mWhere.where());
		}
		return mQueryBuilder.toString();
	}
}
